package com.dayatang.hrm.compensation.service.impl;

import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import com.dayatang.hrm.compensation.service.RuleTemplate;

public class RuleTemplateImpl implements RuleTemplate {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7390258166407025080L;

	private static String ruleHeader;

	private static String salaryCalculateItemDefaultExistRule;

	private static String salaryCalculateItemDefaultNoExistRule;

	private static String normalCalculateRule;

	@Override
	public String getCalculateRuleHeader() {
		if (ruleHeader == null) {
			ruleHeader = readRuleFile("/ruletemplate/RuleHeader.rule", "UTF-8");
		}
		return ruleHeader;
	}

	@Override
	public String getSalaryCalculateItemDefaultExistRule() {
		if (salaryCalculateItemDefaultExistRule == null) {
			salaryCalculateItemDefaultExistRule = readRuleFile(
					"/ruletemplate/SalaryCalculateItem-default-exist.rule",
					"UTF-8");
		}
		return salaryCalculateItemDefaultExistRule;
	}

	@Override
	public String getSalaryCalculateItemDefaultNoExistRule() {
		if (salaryCalculateItemDefaultNoExistRule == null) {
			salaryCalculateItemDefaultNoExistRule = readRuleFile(
					"/ruletemplate/SalaryCalculateItem-default-no-exist.rule",
					"UTF-8");
		}
		return salaryCalculateItemDefaultNoExistRule;
	}

	@Override
	public String getNormalCalculateRule() {
		if (normalCalculateRule == null) {
			normalCalculateRule = readRuleFile(
					"/ruletemplate/NormalCalculateRule.rule", "UTF-8");
		}
		return normalCalculateRule;
	}

	/**
	 * 读classpath中的文件
	 * 
	 * @param location
	 *            文件classpath中的位置
	 * @param encoding
	 * @return
	 */
	private String readRuleFile(String location, String encoding) {

		String fileContent = "";
		InputStream in = RuleTemplateImpl.class
				.getResourceAsStream(location);
		try {
			fileContent = IOUtils.toString(in, encoding);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(in);
		}

		return fileContent;

	}

}
